﻿
using System;
using System.Net;
using System.Net.Sockets;

namespace AsyncEvtEcho
{
    internal interface IEvtArgsPool
    {
        SocketAsyncEventArgs Pop();
        void Push(SocketAsyncEventArgs evtargs);
    }

    sealed class NewEvtArgsPool : IEvtArgsPool
    {
        private EventHandler<SocketAsyncEventArgs> m_ioHandler;
        private volatile int m_counter;

        public NewEvtArgsPool(EventHandler<SocketAsyncEventArgs> ioHandler)
        {
            m_ioHandler = ioHandler;
            m_counter = 0;
        }

        #region [ implement IEvtArgsPool ]

        public SocketAsyncEventArgs Pop()
        {
            ++m_counter;
            Console.WriteLine("[+] new client received, totally, <{0}> clients now", m_counter);

            SocketAsyncEventArgs evtArgs = new SocketAsyncEventArgs();
            evtArgs.Completed += m_ioHandler;

            return evtArgs;
        }

        public void Push(SocketAsyncEventArgs evtargs)
        {
            --m_counter;
            Console.WriteLine("[-] client exits, totally, <{0}> clients now", m_counter);

            evtargs.Completed -= m_ioHandler;
            evtargs.Dispose();
        }

        #endregion
    }
}
